package com.grj.parkingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grj.parkingsystem.common.JwtUtil;
import com.grj.parkingsystem.entity.ParkingOrder;
import com.grj.parkingsystem.entity.User;
import com.grj.parkingsystem.entity.Vehicle;
import com.grj.parkingsystem.mapper.UserMapper;
import com.grj.parkingsystem.mapper.VehicleMapper;
import com.grj.parkingsystem.service.ParkingOrderService;
import com.grj.parkingsystem.mapper.ParkingOrderMapper;
import com.grj.parkingsystem.service.SystemConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
* @author ganru
* @description 针对表【t_parking_order(停车订单表)】的数据库操作Service实现
* @createDate 2025-05-16 16:51:44
*/
@Service
public class ParkingOrderServiceImpl extends ServiceImpl<ParkingOrderMapper, ParkingOrder>
    implements ParkingOrderService{

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private VehicleMapper  vehicleMapper;
    @Autowired
    private ParkingOrderMapper parkingOrderMapper;

    @Override
    public String generateOrderNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return "ORD" + sdf.format(new Date()) + UUID.randomUUID().toString().substring(0, 5);
    }

    @Override
    @Transactional
    public ParkingOrder createEntryOrder(String token, Long parkingLotId, Long spaceId) {
        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        // 查询用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        Vehicle vehicle = vehicleMapper.selectOne(new QueryWrapper<Vehicle>().eq("user_id", user.getId()).eq("is_default", 1));

        ParkingOrder parkingOrder = parkingOrderMapper.selectOne(new QueryWrapper<ParkingOrder>().eq("user_id", user.getId()).eq("parking_lot_id", parkingLotId).eq("vehicle_id", vehicle.getId()).isNull("exit_time"));
        if (parkingOrder != null) {
            return null;
        }
        ParkingOrder order = new ParkingOrder();
        order.setOrderNumber(generateOrderNumber());
        order.setUserId(user.getId());
        order.setVehicleId(vehicle.getId());
        order.setParkingLotId(parkingLotId);
        order.setSpaceId(spaceId);
        order.setEntryTime(new Date());
        order.setOrderStatus(0); // 0: 进行中
        save(order);
        return order;
    }

    @Override
    @Transactional
    public boolean exitParking(String token) {

        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        // 查询用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        Vehicle vehicle = vehicleMapper.selectOne(new QueryWrapper<Vehicle>().eq("user_id", user.getId()).eq("is_default", 1));

        ParkingOrder order = baseMapper.selectOne(new QueryWrapper<ParkingOrder>().eq("user_id", user.getId()).eq("order_status", 0).eq("vehicle_id", vehicle.getId()));

        if (order == null) {
            return false;
        }

        if (!Objects.equals(user.getId(), order.getUserId())) {
            return false;
        }

        if (order.getOrderStatus() != 0) {
            return false;
        }

        Date exitTime = new Date();
        order.setExitTime(exitTime);

        // 计算停车时长（分钟）
        long durationMillis = exitTime.getTime() - order.getEntryTime().getTime();
        int durationMinutes = (int) (durationMillis / (1000 * 60));
        order.setDuration(durationMinutes);

        // 计算费用
        String feeBaseStr = systemConfigService.getConfigValue("parking_fee_base");
        BigDecimal feeBase = new BigDecimal(feeBaseStr);
        BigDecimal hours = new BigDecimal(durationMinutes).divide(new BigDecimal(60), 2, RoundingMode.CEILING);
        BigDecimal originalPrice = feeBase.multiply(hours);
        order.setOriginalPrice(originalPrice);
        order.setActualPrice(originalPrice); // 默认无优惠

        order.setOrderStatus(1); // 1: 已完成

        return updateById(order);
    }

    @Override
    public List<ParkingOrder> getUserOrders(String token, Integer status) {
        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        // 查询用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        return baseMapper.selectList(new QueryWrapper<ParkingOrder>()
                .eq("user_id", user.getId())
                .eq("order_status", status)
                .orderByDesc("create_time"));
    }

    @Override
    public ParkingOrder getOrderDetail(String token, Long orderId) {
        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        // 查询用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user != null) {
            return baseMapper.selectOne(new QueryWrapper<ParkingOrder>().eq("id", orderId).eq("user_id", user.getId()));
        }
        return null;
    }
}




